{% extends '__base__.html' %}

{% block title %}博客{% endblock %}
{% block beforehead %}
<style>
@keyframes fadeIn {
    from {bottom:0%;}
    to {bottom:10%;}
}
.fade-in {
    animation: fadeIn .1s
}

@keyframes fadeOut {
    from {bottom:10%;display: block}
    to {bottom:0%;display: none}
}
.fade-out {
    animation: fadeOut .1s
}

</style>
{% endblock %}
{% block content %}
<!-- Content Header (Page header) -->

<section class="content-header">
    <h1>
        博客
        <small>博客信息管理</small>
    </h1>
    <ol class="breadcrumb">
        <li><a href="/"><i class="fa fa-dashboard"></i> Home</a></li>
        <li class="active">博客</li>
    </ol>
</section>

<div class="container" id="main">
    <router-view></router-view>
</div>
{% endblock %}

{% block beforebody %}
<script src="https://unpkg.com/vue@next"></script>
<script src="https://unpkg.com/vue-router@4"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/layer/3.5.1/layer.js"></script>
<script>
    function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
                var pair = vars[i].split("=");
                if(pair[0] == variable){return pair[1];}
        }
        return(false);
    }
    let toolsbar = {
        delimiters: ['+{', '}'],
        template: `
            <div class="row">
                <nav class="col-md-12" aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item">
                            <a href="/" @click.prevent="pathTo('/')">首页</a>
                        </li>
                        <li v-for="(item, index) in paths" class="breadcrumb-item">
                            <a v-if="index === paths.length - 1" >+{item}</a>
                            <a v-else :href="'/' + paths.slice(0, index + 1).join('/')" @click.prevent="pathTo('/' + paths.slice(0, index + 1).join('/'))">+{item}</a>
                        </li>
                        <li v-if="showMkdir" class="breadcrumb-item">
                            <input type="text" style="height: 20px;width: 80px;border: none;" v-model="newPath">
                            <a class="ml-2" style="cursor: pointer;font-size: 1em;" @click="mkdir"><i class="fa fa-check-circle-o" aria-hidden="true"></i></a>
                        </li>
                        <div class="d-sm-block d-none" v-if="mode !== 'edit'" style="position:absolute;right:50px">
                            <a class="ml-2" href="mkdir" @click.prevent="showMkdir=true">新建目录</a>
                            <a class="ml-2" href="edit" @click.prevent="$router.push({name: 'edit', path: '/edit', params: { path: path }})">新建</a>
                        </div>
                    </ol>
                </nav>
            </div>
            `,
        data() {
            return {
                // paths: this.path ? this.path.slice(1).split('/') : [],
                showMkdir: false,
                newPath: ''
            }
        },
        props: ['path', 'mode'],
        emits: ['pathTo', 'edit', 'mkdir'],
        methods: {
            pathTo(path) {
                this.$emit('pathTo', path)
            },
            mkdir() {
                this.$emit('mkdir', (this.path.endsWith('/') ? this.path : this.path + '/') + this.newPath)
                this.newPath = ''
                this.showMkdir = false
            }
        },
        computed: {
            paths() {
                return this.path && this.path !== '/' ? this.path.slice(1).split('/') : []
            }
        },
        mounted() {
        }
    }

    let operator = {
        delimiters: ['+{', '}'],
        props: ['show'],
        emits: ['deleteItems', 'exportItems', 'importItems', 'close'],
        template: `
            <div ref="opt" :class="classList" :style="styleList">
                <a class="ml-3" style="cursor: pointer;" @click="$emit('deleteItems')"><i class="fa fa-trash-o" aria-hidden="true"></i></a>
                <a class="ml-3" style="cursor: pointer;" @click="$emit('exportItems')"><i class="fa fa-cloud-download" aria-hidden="true"></i></a>
                <a class="ml-3" style="cursor: pointer;" @click="$emit('importItems')"><i class="fa fa-cloud-upload" aria-hidden="true"></i></a>
                <a class="ml-3" style="cursor: pointer;" @click="$emit('close')"><i class="fa fa-times" aria-hidden="true"></i></a>
            </div>
            `,
        data() {
            return {

            }
        },
        methods: {
        },
        computed: {
            classList() {
                return {
                    'p-2': true,
                    'border': true,
                    'border-light': true,
                    'rounded-sm': true,
                    'fade-in1': this.show,
                    'd-none1': !this.show
                }
            },
            styleList() {
                return {
                    position: 'fixed',
                    transition: 'opacity .5s, bottom .5s',
                    bottom: this.show ? '10%' : '0%',
                    transform: 'translate(-50%, -50%)',
                    left: "50%",
                    'font-size': '2em',
                    background: '#fff',
                    opacity: this.show ? '1' : '0'
                }
            }
        }
    }
    let list = {
        // data返回值是暴露的属性
        data() {
            return {
                // path: '',
                items: [],
                page: {'total': 0, 'pages': 1, 'index': 1, 'size': 12},
                pagesize: 1,
                selected: false,
                selectItem: []
            }
        },
        delimiters: ['+{', '}'],
        template: `
            <div class="row">
                <div class="col-12">
                    <div class="card" style="cursor: pointer">
                        <div class="card-header">
                            <div class="row text-center">
                                <div class="col-1"><input type="checkbox" v-model="selected" @click="selectAll"></div>
                                <div class="col-5">
                                    <span v-if="selectItem.length > 0" style="position: absolute;left: 0px">已选择+{selectItem.length + '/' + (this.items ? this.items.length : 0)}</span>
                                    名称
                                </div>
                                <div class="col-2">作者</div>
                                <div class="col">修改时间</div>
                            </div>
                        </div>
                        <ul class="list-group list-group-flush">
                            <li class="list-group-item" v-for="item in items" @click="selectOne(item.id, $event)">
                                <div class="row d-flex align-items-center">
                                    <div class="col-1 text-center"><input type="checkbox" :value="item.id" v-model="selectItem"></div>
                                    <div class="col-5 border-left">
                                        <a v-if="item.content_type === 'd'" @click.prevent="pathTo((item.path.endsWith('/') ? item.path : item.path + '/') + item.name)"><span><i class="fa fa-folder-o mr-1" aria-hidden="true"></i>+{item.name}</span></a>
                                        <a v-if="item.content_type === '-'" @click.prevent="$router.push({name: 'view', path: '/view', params: {path: item.path, id: item.id}})"><span><i class="fa fa-book mr-1" aria-hidden="true"></i>+{item.name}</span></a>
                                    </div>
                                    <div class="col-3 border-left">
                                        <div>+{item.author}</div>
                                        <div class="small"><span class="d-none d-md-block">+{item.updated_at}</span><span class="d-block d-md-none">+{item.updated_at.split(' ')[0]}</span></div>
                                    </div>
                                    <div class="col-3 border-left"><span class="d-none d-lg-block">+{item.updated_at}</span><span class="d-block d-lg-none">+{item.updated_at.split(' ')[0]}</span></div>
                                </div>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="row user-select-none" style="cursor: pointer;">
                <nav class="col-4" aria-label="Page navigation example">
                    <ul class="pagination">
                        <li class="page-item" :class="{disabled: page.index == 1}">
                            <a class="page-link"
                                @click="loadItems(page.index - 1)"
                                aria-label="Previous">
                                <span aria-hidden="true">«</span>
                            </a>
                        </li>
                        <li class="page-item" v-for="index in range" :class="{disabled: index==page.index}">
                            <a class="page-link" @click="loadItems(index)"> +{index}</a>
                        </li>
                        <li class="page-item" :class="{disabled: page.index == page.pages}">
                            <a class="page-link"
                                @click="loadItems(page.index + 1)"
                                aria-label="Next">
                                <span aria-hidden="true">»</span>
                            </a>
                        </li>
                        <li class="page-item ">
                            <input @keyup.enter="loadItems($event.currentTarget.value)" class="page-link" style="width:50px">
                        </li>
                        <li class="page-item disabled">
                            <input class="page-link text-center" style="width:70px" :value="page.index + '/' + page.pages">
                        </li>
                        <li class="page-item disabled">
                            <input class="page-link text-center" style="width:70px" value="每页: ">
                        </li>
                        <li class="page-item">
                            <input class="page-link text-center" style="width: 80px;" type="number" min="1" max="100" v-model="pagesize">
                        </li>
                    </ul>
                </nav>
            </div>
            <operator :show="selectItem.length > 0"
                @delete-items="deleteItems"
                @export-items="exportItems"
                @import-items="importItems"
                @close="selectItem = []" />
            `,
        components: {
            operator: operator,
        },
        props: ['blog_path'],
        emits: ['pathTo'],
        mounted() {
            let page = localStorage.getItem('blog.page')
            if (page != null && page != 'null' && page != undefined && page != 'undefined') {
                this.page = JSON.parse(page)
            }
            this.loadItems(1)
            this.pagesize = this.page.size
        },
        watch: {
            pagesize(newVal, oldVal) {
                // console.log(newVal, oldVal)
                this.page.size = this.pagesize
                localStorage.setItem('user.page', JSON.stringify(this.page))
            },
            selectItem(newVal, oldVal) {
                // console.log(newVal, oldVal)
                if (newVal.length === this.items.length) {
                    this.selected = true
                } else {
                    this.selected = false
                }
                if (newVal.length === 0) {
                }
                layer.closeAll()
                if (newVal.length > 0) {
                    /*
                    layer.closeAll()
                    let index = layer.open({
                        type: 1,
                        title: false,
                        content: 'this.$refs.opt.firstChild.outerHTML',
                        shadeClose: true,
                        // time: 3000,
                        shade: 0,
                        resize: false,
                        anim: 2,
                        offset: '75vh',
                        cancel: ()=>{
                            this.selectItem = []
                        }
                    })
                    */
                }
            },
            blog_path(newVal, oldVal) {
                // console.log([newVal, oldVal])
                this.loadItems(1)
            },
        },
        updated() {
        },
        methods: {
            formatItem(item) {
                let result = {}
                for (key in item) {
                    // console.log(item[key])
                    result[key] = isJSON(item[key])?this.formatItem(JSON.parse(item[key])):item[key]
                    // result[key] = item[key]
                }
                return result
            },
            loadItems(index, pagesize=12) {
                // console.log('<--', this.blog_path)
                axios.get('/blog/page', {
                        params: {
                            index: index,
                            pagesize: this.page.size,
                            path: this.blog_path,
                        }
                    })
                    .then(
                        response => {
                            if (response.status === 200) {
                                let data = response.data
                                if (data['code'] === 0) {
                                    this.items = data['msg']['items'] ? data['msg']['items'] : this.items
                                    this.page = data['msg']['page'] ? data['msg']['page'] : this.page
                                    this.path = data['msg']['path']
                                } else {
                                    console.log('FAILED: ' + data['msg'])
                                }
                            }
                        })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            selectAll(){
                if (this.selected) {
                    this.selectItem = []
                } else {
                    this.selectItem = []
                    this.items.forEach(el => {
                        this.selectItem.push(el.id)
                    })
                }
            },
            selectOne(id, event) {
                if (event.target.tagName === "INPUT") return
                this.selectItem = []
                this.selectItem.push(id)
            },
            pathTo(path) {
                this.$emit('pathTo', path)
            },
            deleteItems() {
                console.log(this.selectItem)
            },
            importItems() {
                console.log(this.selectItem)
            },
            exportItems() {
                console.log(this.selectItem)
            },
        },
        computed: {
            pageSize() {
                return this.page.size
            },
            range() {
                range = []
                if (this.page.pages <= 5) {
                    for (let i = 1; i <= this.page.pages; ++i) {
                        range.push(i)
                    }
                } else {
                    if (this.page.index <= 3) {
                        for (let i = 1; i <= 5; ++i) {
                            range.push(i)
                        }
                    }
                    if (this.page.index > 3 && this.page.index < this.page.pages - 2) {
                        for (let i = this.page.index - 2; i <= this.page.index + 2; ++i) {
                            range.push(i)
                        }
                    }
                    if (this.page.index >= this.page.pages - 2) {
                        for (let i = this.page.pages - 4; i <= this.page.pages; ++i) {
                            range.push(i)
                        }
                    }
                }
                if (range.length === 0) range = [1]
                return range
                // console.log(this.range)
            }
        }
    }
    let index = {
        delimiters: ['+{', '}'],
        template: `
            <div>
                <div class="row">
                    <nav class="col-md-12" aria-label="breadcrumb">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item">
                                <a href="/" @click.prevent="pathTo('/')">首页</a>
                            </li>
                            <li v-for="(item, index) in paths" class="breadcrumb-item">
                                <a v-if="index === paths.length - 1" >+{item}</a>
                                <a v-else :href="'/' + paths.slice(0, index + 1).join('/')" @click.prevent="pathTo('/' + paths.slice(0, index + 1).join('/'))">+{item}</a>
                            </li>
                            <li v-if="showMkdir" class="breadcrumb-item">
                                <input type="text" style="height: 20px;width: 80px;border: none;" v-model="newPath">
                                <a class="ml-2" style="cursor: pointer;font-size: 1em;" @click="mkdir"><i class="fa fa-check-circle-o" aria-hidden="true"></i></a>
                                <a class="ml-2" style="cursor: pointer;font-size: 1em;" @click="showMkdir=false;newPath=''"><i class="fa fa-close" aria-hidden="true"></i></a>
                            </li>
                            <div class="d-sm-block d-none" style="position:absolute;right:50px">
                                <a class="ml-2" href="mkdir" @click.prevent="showMkdir=true">新建目录</a>
                                <a class="ml-2" href="edit" @click.prevent="$router.push({name: 'edit', path: '/edit', params: { path: path }})">新建</a>
                            </div>
                        </ol>
                    </nav>
                </div>
                <list @path-to="pathTo" :blog_path='path'></list>
            </div>`,
        components: {
            list: list,
        },
        props: ['blogpath'],
        data() {
            return {
                path: '/',
                showMkdir: false,
                newPath: ''
            }
        },
        mounted() {
            if (this.blogpath) {
                console.log('-->', this.blogpath)
                this.path = this.blogpath
            }
        },
        computed: {
            paths() {
                return this.path && this.path !== '/' ? this.path.slice(1).split('/') : []
            }
        },
        methods: {
            pathTo(path) {
                this.path = path
            },
            mkdir() {
                let path = (this.path.endsWith('/') ? this.path : this.path + '/') + this.newPath
                if (!path || path.length <= 0 || path === '/') return
                axios.post('/blog/mkdir', {
                        path: path
                    })
                    .then(
                        response => {
                            if (response.status === 200) {
                                let data = response.data
                                if (data['code'] === 0) {
                                    this.path = path
                                    this.newPath = ''
                                    this.showMkdir = false
                                } else {
                                    console.log('FAILED: ' + data['msg'])
                                    layer.msg(data['msg'])
                                }
                            }
                        })
                    .catch(function (error) {
                        console.log(error);
                    });
            }
        },
    }

    let view = {
        delimiters: ['+{', '}'],
        template: `
            <div>
                <div class="row">
                    <nav class="col-md-12" aria-label="breadcrumb">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item">
                                <a href="/" @click.prevent="pathTo('/')">首页</a>
                            </li>
                            <li v-for="(item, index) in paths" class="breadcrumb-item">
                                <a :href="'/' + paths.slice(0, index + 1).join('/')" @click.prevent="pathTo('/' + paths.slice(0, index + 1).join('/'))">+{item}</a>
                            </li>
                            <li v-if="name !== undefined" class="breadcrumb-item">
                                <a>+{name}</a>
                            </li>
                            <div class="d-sm-block d-none" style="position:absolute;right:50px">
                                <a class="ml-2" href="mkdir" @click.prevent="$router.push({name: 'edit', path: '/edit', params: {path: path, id: id}})">编辑</a>
                            </div>
                        </ol>
                    </nav>
                </div>
                <div class="row">
                    <div class="col-12" style="height: 50vh;background-color: rgba(153, 245, 191, 0.98);overflow-y: scroll;">+{view}</div>
                    <input disabled v-model="name" class="col-7 mt-1" placeholder="日志名称">
                    <textarea disabled v-model="summary" class="col-7 mt-2" cols="3" placeholder="摘要" style="resize: none;"></textarea>
                    <input type="hidden" :value="id!==undefined?id:''">
                </div>
            </div>
            `,
        components: {
        },
        data() {
            return {
                view: '',
                name: '',
                summary: '',
            }
        },
        props: ['path', 'id'],
        emits: ['pathTo'],
        computed: {
            paths() {
                return this.path && this.path !== '/' ? this.path.slice(1).split('/') : []
            }
        },
        methods: {
            pathTo(path) {
                this.$router.push({name: 'index', path: '/', params: { blogpath: path }})
            },
            loadItem() {
                if (!this.id) return
                axios.get('/blog/item', {
                        params: {
                            id: this.id
                        }
                    })
                    .then(
                        response => {
                            if (response.status === 200) {
                                let data = response.data
                                if (data['code'] === 0) {
                                    let item = data['msg']['item']
                                    this.view = item.content
                                    this.name = item.name
                                    this.summary = item.summary
                                } else {
                                    console.log('FAILED: ' + data['msg'])
                                    layer.msg(data['msg'])
                                }
                            }
                        })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
        },
        mounted() {
            this.loadItem(this.id)
        },
        computed: {
            paths() {
                return this.path && this.path !== '/' ? this.path.slice(1).split('/') : []
            }
        }
    }
    let edit = {
        delimiters: ['+{', '}'],
        template: `
            <div>
                <div class="row">
                    <nav class="col-md-12" aria-label="breadcrumb">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item">
                                <a href="/" @click.prevent="pathTo('/')">首页</a>
                            </li>
                            <li v-for="(item, index) in paths" class="breadcrumb-item">
                                <a :href="'/' + paths.slice(0, index + 1).join('/')" @click.prevent="pathTo('/' + paths.slice(0, index + 1).join('/'))">+{item}</a>
                            </li>
                            <li v-if="name !== undefined" class="breadcrumb-item">
                                <a href="/" @click.prevent="$router.push({name: 'view', path: '/view', params: { path: path, id: id }})">+{name}</a>
                            </li>
                            <div class="d-sm-block d-none" style="position:absolute;right:50px">
                                <a class="ml-2" href="mkdir" @click.prevent="save">保存</a>
                            </div>
                        </ol>
                    </nav>
                </div>
                <div class="row">
                    <textarea v-model="text" class="col-6" style="height: 50vh;resize: none;"></textarea>
                    <div class="col-6" style="height: 50vh;background-color: rgba(153, 245, 191, 0.98);overflow-y: scroll;">+{view}</div>
                    <input :disabled="id!==undefined" v-model="name" class="col-7 mt-1" placeholder="日志名称">
                    <textarea v-model="summary" class="col-7 mt-2" cols="3" placeholder="摘要" style="resize: none;"></textarea>
                    <input type="hidden" :value="id!==undefined?id:''">
                </div>
            </div>
            `,
        components: {
        },
        data() {
            return {
                text: '',
                view: '',
                name: '',
                summary: '',
            }
        },
        props: ['path', 'id'],
        emits: ['pathTo'],
        computed: {
            paths() {
                return this.path && this.path !== '/' ? this.path.slice(1).split('/') : []
            }
        },
        methods: {
            pathTo(path) {
                this.$router.push({name: 'index', path: '/', params: { blogpath: path }})
            },
            loadItem() {
                if (!this.id) return
                axios.get('/blog/item', {
                        params: {
                            id: this.id
                        }
                    })
                    .then(
                        response => {
                            if (response.status === 200) {
                                let data = response.data
                                if (data['code'] === 0) {
                                    let item = data['msg']['item']
                                    this.text = item.content
                                    this.view = ''
                                    this.name = item.name
                                    this.summary = item.summary
                                } else {
                                    console.log('FAILED: ' + data['msg'])
                                    layer.msg(data['msg'])
                                }
                            }
                        })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            save() {
                console.log(this.path)
                axios.post('/blog/save', {
                        id: this.id,
                        name: this.name,
                        content: this.text,
                        summary: this.summary,
                        path: this.path,
                    })
                    .then(
                        response => {
                            if (response.status === 200) {
                                let data = response.data
                                if (data['code'] === 0) {
                                    console.log('SUCCESS: ' + JSON.stringify(data['msg']))
                                    this.$router.push({name: 'edit', path: '/edit', params: { path: this.path, id: data['msg']['id'] }})
                                } else {
                                    console.log('FAILED: ' + data['msg'])
                                }
                                layer.msg(JSON.stringify(data['msg']))
                            }
                        })
                    .catch(function (error) {
                        console.log(error);
                    });
            }
        },
        mounted() {
            this.loadItem(this.id)
        },
    }
    const routes = [
        {
            path: '',
            name: 'index',
            component: index,
            props: resp => ({blogpath: resp.params.blogpath})
        },
        {
            path: '/edit',
            name: 'edit',
            component: edit,
            props: resp => ({path: resp.params.path, id: resp.params.id})
        },
        {
            path: '/view',
            name: 'view',
            component: view,
            props: resp => ({path: resp.params.path, id: resp.params.id})
        }
    ]
    const router = VueRouter.createRouter({
        // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
        history: VueRouter.createWebHashHistory(),
        routes, // `routes: routes` 的缩写
    })
    const app = Vue.createApp({})
    //整个应用支持路由。
    app.use(router)
    // mount方法返回根组件实例
    const vm = app.mount('#main')
    console.log(vm)
</script>
{% endblock %}